﻿using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

namespace WebMiddleware.SaveInfoService
{
    public static class JsonConfigFileHelper
    {
        public static TModel Read<TModel>(Stream stream) where TModel : class, new()
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes);
            return JsonSerializer.Deserialize<TModel>(bytes) ?? throw new InvalidOperationException();
        }

        public static void Write<TModel>(Stream stream, TModel model) where TModel : class, new()
        {
            stream.SetLength(0); // 清空文件流内容。
            JsonSerializer.Serialize(new Utf8JsonWriter(stream), model);
            stream.Flush();
        }

        public static async Task<TModel> ReadAsync<TModel>(Stream stream) where TModel : class, new()
        {
            return await JsonSerializer.DeserializeAsync<TModel>(stream) ?? throw new InvalidOperationException();
        }

        public static async Task<TModel> ReadAsync<TModel>(string fileName) where TModel : class, new()
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(fileName);
            }

            using var fileStream = File.OpenRead(fileName);
            return await JsonSerializer.DeserializeAsync<TModel>(fileStream) ?? throw new InvalidOperationException();
        }

        public static async Task WriteAsync<TModel>(Stream stream, TModel model) where TModel : class, new()
        {
            stream.SetLength(0); // 清空文件流内容。
            await JsonSerializer.SerializeAsync(stream, model);
            await stream.FlushAsync();
        }

        public static async Task WriteAsync<TModel>(string fileName, TModel model) where TModel : class, new()
        {
            using var fileStream = File.OpenWrite(fileName);
            fileStream.SetLength(0); // 清空文件流内容。
            await JsonSerializer.SerializeAsync(fileStream, model);
            await fileStream.FlushAsync();
        }
    }
}
